
class UsersController < ApplicationController
  require 'kaminari'
  def show
    @user = User.find(params[:id])
    puts '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' 
    puts params 
    puts 'L_____________________|'

    if params[:page]
      @microposts = @user.microposts.page(:page => params[:page]).per(10) 
    else
      @microposts = @user.microposts.page(1)
    end

    puts 'Microposts !'
    puts @microposts

    @title = @user.name
  end

  def new
    @user  = User.new
    @title = "Sign up"
  end
  
  def find
    User.new
  end

  def edit
    @user = User.find(params[:id])
    @title = "Edit user"
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      flash[:success] = "Welcome to the Sample App!"
      redirect_to @user
    else
      @title = "Sign up"
      flash.now[:error] = "Cannot register: #{@user.errors.full_messages}"
      render 'new'
      logger.debug @user
    end
  end

  def has_password?(submitted_password)
    encrypted_password == encrypt(submitted_password)
  end

  def self.authenticate(email, submitted_password)
    user = find_by_email(email)
    return nil  if user.nil?
    return user if user.has_password?(submitted_password)
  end

   def update
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      flash[:success] = "Profile updated."
      redirect_to @user
    else
      @title = "Edit user"
      render 'edit'
    end
  end


  def index
    @title = "All users"
    @users = User.page(:page => params[:page])
  end

  before_filter :authenticate, :only => [:edit, :update, :index, :destroy]
  before_filter :correct_user, :only => [:edit, :update]
  before_filter :admin_user,   :only => :destroy

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User destroyed."
    redirect_to users_path
  end


  private
    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_path) unless current_user?(@user)
    end
   
    def admin_user
      redirect_to(root_path) unless current_user.admin?
    end
end
